<?


/* Init & Config
**************************************************/

// Load classes
include_once('includes/loader.inc.php');

//printer($_REQUEST);

// Set the theme
$theme = CONFIG_THEME;

// Set the default access level
$all_access = CONFIG_ALL_ACCESS;

// Set defaults
$default_section = current(array_keys($sections));
$defaults = array(
	"section" => $default_section,
	"action" => $sections[$default_section]["default_action"]
);

/* Get URL data
**************************************************/

$rec = Helpers::route($_GET["params"], $routes);
$rec = array_merge($defaults, $rec);

$section  = $rec["section"];
$action  = $rec["action"];
$params = $rec["params"];

// Table options
$options = array('table' => $section);
if ($sections[$section])
	$options = $sections[$section];

// Set limit
if (!$options["limit"])
	$options["limit"] = CONFIG_LIST_LIMIT;



/* Get REQUEST data
**************************************************/

$request = array("id", "search", "section", "action", "url", "data", "location");
foreach ($request as $key) {
	if ($_REQUEST[$key]) {
		${$key} = $_REQUEST[$key];
	}
}
if ($_REQUEST["id"])
	$params["id"] = $id;



/* Check user access
***************************************************/

// Check if user is logged
$user = new User();
if (!$user->logged()) {
	include('themes/' . CONFIG_THEME . '/login.tpl');
	exit;
}

// Set ACL
$acl = ($acl)? $acl : $sections[$section]['acl'];
if (is_array($acl)) {
	foreach ($acl as $value) {
		$acl[$value] = true;
	}
}

// Set constants
define('ROUTE', $session->get('route') . "/");
define('URL', $session->get('route') . "/" . $options["table"] . "/");
define('ACTION', $action);
define('SECTION', $section);

// Define location for redirects
$location = ($location)? $location : URL; 
define('LOCATION', $location);

// Check ACL
if (!$all_access && !$acl[$action])
	Helpers::end('You are not allowed to do this action.');



/* Search
***************************************************/

if ($search) {
	$url = URL . 'browse/';
	foreach($search as $key => $value) {
		$value = addslashes($value);
		if ($value != '') {
			$url .=  $key . ':' . $value . '/';
		}
	}
	header("Location: $url");
	exit;
}




/* Call controller
**************************************************/

// Set controller or use default
$classname = $section . "_controller";
if (class_exists($classname)) {
	$obj = new $classname();
} else {
	$obj = new Controller();
}

// Call controller with two important values:

// $options: The general options of the table and its joins.
// array("table" => "books", "acl" => array("browse", "details", "add") ... ) 

// $params: The params for this method call.
// array("limit" => 8, "page" => 2, "filters" => array("author", "LIKE", "Robinson") ... )

call_user_func_array(array($obj, $action), array($options, $params, $data));



?>